<template>
  <div class="app-container">
    <el-form :inline="true">
      <el-form-item label="执行器" prop="请选择执行器">
        <el-select size="small" v-model="queryParams.jobGroup" @change="groupChange" filterable
                   placeholder="请选择执行器"
        >
          <el-option value="0" key="0" label="全部"></el-option>
          <el-option
            v-for="item in groupListData"
            :key="item.id"
            :label="item.title"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="任务" prop="请选择任务">
        <el-select size="small" v-model="queryParams.jobId" placeholder="请选择任务" clearable>
          <el-option key="0" value="0" label="全部"></el-option>
          <el-option
            v-for="item in jobs"
            :key="item.id"
            :label="item.jobDesc"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="日志状态" prop="请选择日志状态">
        <el-select size="small" v-model="queryParams.logStatus" placeholder="请选择日志状态">
          <el-option
            v-for="item in statusEnum"
            :key="item.code"
            :label="item.msg"
            :value="item.code"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          size="small"
          v-model="queryParams.timeScope"
          type="datetimerange"
          range-separator="~"
          value-format="yyyy-MM-dd HH:mm:ss"
          editable
          clearable
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="getLogList">查询</el-button>
        <el-button type="primary" size="small" @click="clearJobLogs" v-hasPermi="['xxl:job:log:remove']">清除日志</el-button>
      </el-form-item>
    </el-form>
    <el-table
      ref="list"
      :key="tableKey"
      :data="logTableList"
      v-loading="listLoading"
      element-loading-text="数据加载中，请稍后"
      border
      fit
      highlight-current-row
      select-on-indeterminate
      style="width: 100%"
    >

      <el-table-column align="center" label="任务ID" min-width="60">
        <template slot-scope="scope">
          <el-button type="text" @click="jobDetail(scope.row)">{{ scope.row.jobId }}</el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" label="jobHandler" min-width="80">
        <template slot-scope="scope">
          <span class="link-type">{{ scope.row.executorHandler }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="调度时间" min-width="120">
        <template slot-scope="scope">
          <span class="link-type">{{ parseTime(scope.row.triggerTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column min-width="40" align="center" label="调度结果" show-overflow-tooltip>
        <template slot-scope="scope">
          <span :class="{'sucColor':scope.row.triggerCode===200,'failColor':scope.row.triggerCode===500}">
            {{ scope.row.triggerCode === 200 ? '成功' : (scope.row.triggerCode === 500 ? '失败' : '') }}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="40" align="center" label="调度备注" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-button type="text" @click="triggerMsgDetail(scope.row)">查看</el-button>
        </template>
      </el-table-column>

      <el-table-column min-width="100" align="center" label="执行时间" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.handleTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column min-width="40" align="center" label="执行结果" show-overflow-tooltip>
        <template slot-scope="scope">
          <span :class="{'sucColor':scope.row.handleCode===200,'failColor':scope.row.handleCode===500}">
            {{ scope.row.handleCode === 200 ? '成功' : (scope.row.handleCode === 500 ? '失败' : '') }}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="40" align="center" label="执行备注" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ scope.row.handleMsg === '' ? '无' : scope.row.handleMsg }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="60">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" v-show="scope.row.triggerCode===200" @click="exeLogDetail(scope.row)">
            日志详情
          </el-button>
          <el-button size="mini" type="danger" v-show="scope.row.triggerCode===200 && scope.row.handleCode===0"
                     v-hasPermi="['xxl:job:log:kill']"
                     @click="stopJob(scope.row.id)"
          >终止
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page.sync="queryParams.currentPage"
                     :page-sizes="[10,20,30,50]" :page-size="queryParams.length"
                     layout="total, sizes, prev, pager, next, jumper" :total="total"
      >
      </el-pagination>
    </div>

    <el-dialog class="dialog-detail-view" title="执行日志" custom-class="detail-dialog" width="60%"
               :visible.sync="dialogFormVisible" center @close="onCloseDetail"
    >
      <pre v-html="jobLogDetail.logContent"></pre>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogFormVisible = false">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="清除执行器日志" :visible.sync="clearLogDialog" center>
      <el-form :model="clearForm" :rules="rules" ref="clearForm">
        <el-form-item class="clear-log-form-view" label="执行器" prop="jobGroup">
          <el-select v-model="clearForm.jobGroup" @change="groupClearChange" placeholder="请选择执行器">
            <el-option value="0" key="0" label="全部"></el-option>
            <el-option
              v-for="item in groupListData"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="clear-log-form-view" label="任务" prop="jobId" clearable>
          <el-select v-model="clearForm.jobId" placeholder="请选择任务">
            <el-option value="0" key="0" label="全部"></el-option>
            <el-option
              v-for="item in clearJobs"
              :key="item.id"
              :label="item.jobDesc"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="clear-log-form-view" label="清理方式" prop="type">
          <el-select v-model="clearForm.type" placeholder="请选择清理方式">
            <el-option
              v-for="item in logTimeEnum"
              :key="item.code"
              :label="item.msg"
              :value="item.code"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="clearLogDialog = false">取 消</el-button>
        <el-button type="primary" @click="exeClearLogs">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getGroupList } from '@/api/xxlJob/group'
import { clearLogs, getJobDetail, getLogsList, stopJob, getJobsByGroup } from '@/api/xxlJob/logs'
import qs from 'qs'
import { formartUstTime } from '@/utils'

export default {
  name: 'LogList',
  props: {},
  components: {},
  data() {
    return {
      statusEnum: [{ code: -1, msg: '全部' }, { code: 1, msg: '成功' }, { code: 2, msg: '失败' }, { code: 3, msg: '进行中' }],
      groupListData: [],
      jobs: [],
      clearJobs: [],
      dialogStatus: 'create',
      dialogFormVisible: false,
      clearLogDialog: false,
      modifyData: '',
      logTableList: null,
      total: null,
      listLoading: true,
      queryParams: {
        currentPage: 1,
        jobGroup: '0',
        jobId: '0',
        start: 0,
        length: 10,
        logStatus: -1,
        filterTime: '', //[new Date(2000, 10, 10, 10, 10), new Date(2000, 10, 11, 10, 10)],
        timeScope: []
      },
      tableKey: 0,
      // 刷新定时器
      detailTailTimer: null,
      jobLogDetail: {
        logContent: ''
      },
      logTimeEnum: [{ code: 1, msg: '一个月前' }, { code: 2, msg: '三个月前' }, { code: 3, msg: '六个月前' }, {
        code: 4,
        msg: '一年之前'
      },
        { code: 5, msg: '一千条之前' }, { code: 6, msg: '一万条之前' }, { code: 7, msg: '三万条之前' }, {
          code: 8,
          msg: '十万条之前'
        }, { code: 9, msg: '所有' }],
      clearForm: {
        jobGroup: '0',
        jobId: '0',
        // logStatus: null,
        type: 1
      },
      rules: {
        groupListData: [{ required: true, message: '请选择执行器', trigger: 'blur' }],
        jobId: [{ required: true, message: '请选择任务', trigger: 'blur' }],
        type: [{ required: true, message: '请选择时间段', trigger: 'blur' }]
      }, pickerOptions: {
        shortcuts: [{
          text: '今日',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setHours(0)
            start.setMinutes(0)
            start.setSeconds(0)

            end.setDate(end.getDate() + 1)
            end.setHours(0)
            end.setMinutes(0)
            end.setSeconds(0)
            end.setTime(end.getTime() - 1000)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            start.setHours(0)
            start.setMinutes(0)
            start.setSeconds(0)

            end.setDate(end.getDate() + 1)
            end.setHours(0)
            end.setMinutes(0)
            end.setSeconds(0)
            end.setTime(end.getTime() - 1000)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            start.setHours(0)
            start.setMinutes(0)
            start.setSeconds(0)
            end.setDate(end.getDate() + 1)
            end.setHours(0)
            end.setMinutes(0)
            end.setSeconds(0)
            end.setTime(end.getTime() - 1000)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            start.setHours(0)
            start.setMinutes(0)
            start.setSeconds(0)
            end.setDate(end.getDate() + 1)
            end.setHours(0)
            end.setMinutes(0)
            end.setSeconds(0)
            end.setTime(end.getTime() - 1000)
            picker.$emit('pick', [start, end])
          }
        }]
      }

    }
  },
  created() {
  },
  mounted() {
    this.getLogList()
    this.fetchGroupList()
  },
  watch: {
    'jobLogDetail.logContent': function(val, oldVal) {
      const reg = RegExp('.*xxl-job job callback finish.\\n$')
      if (val.match(reg) && this.detailTailTimer != null) {
        console.info('clean interval ', this.detailTailTimer)
        clearInterval(this.detailTailTimer)
        this.detailTailTimer = null
      }
    }
  },
  methods: {
    getLogList() {
      //对象深拷贝，去除属性
      let params = JSON.parse(JSON.stringify(this.queryParams))
      if (params.timeScope.length > 0) {
        params.filterTime = params.timeScope[0] + ' - ' + params.timeScope[1]
        params.timeScope = null
        params.currentPage = null
      }
      getLogsList(params).then(res => {
        const { data, recordsTotal } = res
        this.listLoading = false
        this.logTableList = data
        this.total = recordsTotal
        if (this.total === 0) {
          this.$message({
            message: '检索结果为空',
            type: 'warning'
          })
        }
      }).catch(function(err) {
        console.log(err)
      })
    },
    //获取执行器
    fetchGroupList() {
      getGroupList(qs.stringify(this.groupQuery)).then(res => {
          const { data, recordsTotal } = res
          this.groupListData = data
          if (recordsTotal === 0) {
            this.$message({
              message: '执行器列表为空,需要先创建执行器',
              type: 'warning'
            })
            return
          }
      }).catch(function(err) {
        console.log(err)
      })
    },
    groupChange() {
      this.queryParams.jobId = '0'
      if (this.queryParams.jobGroup !== '0') {
        getJobsByGroup(this.queryParams.jobGroup).then(res => {
          const { code, content } = res
          if (res.code === 200) {
            this.jobs = content
          }
        }).catch(function(err) {
          console.log(err.message)
        })
      }
    },
    groupClearChange() {
      this.clearForm.jobId = '0'
      if (this.clearForm.jobGroup !== null) {
        getJobsByGroup(this.clearForm.jobGroup).then(res => {
          const { code, content } = res
          if (res.code === 200) {
            this.clearJobs = content
          }
        }).catch(function(err) {
          console.log(err.message)
        })
      }
    },
    stopJob(id) {
      stopJob(id).then(res => {
        const { code, msg } = res
        if (code === 200) {
          this.$message({
            message: '终止成功',
            type: 'success'
          })
        } else {
          this.$message({
            message: '终止失败',
            type: 'warning'
          })
        }
        this.getLogList();
      }).catch(function(err) {
        console.log(err.message)
      })
    },
    exeLogDetail(row) {
      let params = {
        'executorAddress': row.executorAddress,
        'triggerTime': new Date(row.triggerTime).getTime(),
        'logId': row.id,
        'fromLineNum': 1
      }
      this.logTail(params)
      this.detailTailTimer = setInterval(() => {
        getJobDetail(params).then(res => {
          this.jobLogDetail = res.content
          if (res.code === 200) {
            this.dialogFormVisible = true
          } else {
            this.$message({
              message: '查询失败',
              type: 'warning'
            })
          }
        }).catch(function(err) {
          console.log(err.message)
        })
      }, 2000)
      console.info(this.detailTailTimer)
    },
    logTail(params) {
      getJobDetail(params).then(res => {
        this.jobLogDetail = res.content
        if (res.code === 200) {
          this.dialogFormVisible = true
        } else {
          this.$message({
            message: '查询失败',
            type: 'warning'
          })
        }
      }).catch(function(err) {
        console.log(err.message)
      })
    },
    onCloseDetail() {
      if (this.detailTailTimer != null) {
        this.onCloseDetail = null
        clearInterval(this.detailTailTimer)
      }
    },
    clearJobLogs() {
      this.clearLogDialog = true
    },
    exeClearLogs() {
      this.$refs['clearForm'].validate((valid) => {
        if (valid) {
          clearLogs(this.clearForm).then(res => {
            if (res.code === 200) {
              this.$message({
                message: '清除成功',
                type: 'success'
              })
              this.clearLogDialog = false
              this.handleRefresh()
            } else {
              this.$message({
                message: '清除失败',
                type: 'warning'
              })
            }
          }).catch(function(err) {
            console.log(err.message())
          })
        }
      })
    },
    handleFilter() {
      this.queryParams.start = 1
      this.getLogList()
    },
    handleSizeChange(val) {
      this.queryParams.length = val
      this.getLogList()
    },
    handleCurrentChange(val) {
      this.queryParams.start = (val - 1) * this.queryParams.length
      this.getLogList()
    },
    handleRefresh() {
      this.list = null
      this.total = null
      this.queryParams.start = 0
      this.getLogList()
    },
    triggerMsgDetail(row) {
      this.$alert(row.triggerMsg, '调度备注', {
        dangerouslyUseHTMLString: true,
        closeOnPressEscape: true
      }).catch(() => {
      })
    },
    jobDetail(row) {
      let desc = '执行器地址：' + row.executorAddress + '<br>' +
        'JobHandler：' + row.executorHandler + '<br>' +
        '任务参数：' + row.executorParam
      this.$alert(desc, '任务描述', {
        dangerouslyUseHTMLString: true,
        closeOnPressEscape: true
      }).catch(() => {
      })
    },
    formartHandlerTime(time) {
      console.log('=========')
      console.log(time)
      if (time == null || time === undefined) {
        return '-'
      }
      return formartUstTime(time)
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" slot-scope>
.app-container {
  padding: 20px;
}

.pagination-container {
  margin-top: 30px;
}

.fitersLine {
  .el-select .el-input {
    width: 135px;
  }
}

.detail-dialog {
  pre {
    overflow: auto;
    word-break: break-all;
    word-wrap: break-word;
    display: block;
    font-size: 12px;
    font-weight: 400;
  }
}
</style>
<style rel="stylesheet/scss" lang="scss">
.clear-log-form-view {
  .el-select {
    width: 80%;
  }
}

.sucColor {
  color: seagreen;
}

.failColor {
  color: #f56c6c;
}

.top {
  padding: 10px;
}

.el-form--inline .el-form-item {
  margin-right: 2px;
}

.drop-down-view {
  .el-dropdown {
    vertical-align: top;
  }

  .el-dropdown + .el-dropdown {
    margin-left: 15px;
  }

  .el-icon-arrow-down {
    font-size: 12px;
  }

  .el-button {
    padding: 8px 7px;
  }

}

.el-button--mini {
  padding: 7px 10px;
}

.el-button + .el-button {
  margin-left: 1px;
}

.dialog-detail-view {
  .el-form-item {
    margin-bottom: 0px;
  }

  .el-form-item__content {
    line-height: 30px;
  }

  .el-form-item__label {
    line-height: 30px;
  }
}

.el-dialog__header {
  padding-bottom: 0;
}

.el-dialog__body {
  padding: 0
}

.createPost-main-container {
  padding: 20px 0 !important;
}

.fitersLine {
  .el-form-item__content {
    margin-left: 0 !important
  }

  .el-form-item__label {
    min-width: auto !important;
  }

  .el-select {
    margin-top: 3px;
  }
}
</style>
